package com.shioirikukuri.service.impl;

import com.shioirikukuri.entity.CouponType;
import com.shioirikukuri.entity.UserCoupon;
import com.shioirikukuri.entity.UserMember;
import com.shioirikukuri.mapper.CouponTypeMapper;
import com.shioirikukuri.mapper.UserCouponMapper;
import com.shioirikukuri.mapper.UserMemberMapper;
import com.shioirikukuri.service.IUserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserCouponServiceImpl implements IUserCouponService {
	@Autowired
	private UserCouponMapper userCouponMapper;

	@Autowired
	private CouponTypeMapper couponTypeMapper;

	@Autowired
	private UserMemberMapper userMemberMapper;

	@Override
	public void createUserCoupon(UserCoupon userCoupon) {
		userCouponMapper.insertUserCoupon(userCoupon);
	}

	@Override
	public UserCoupon getUserCouponById(Long id) {
		return userCouponMapper.selectUserCouponById(id);
	}

	@Override
	public List<UserCoupon> getUserCouponsByUserId(Long userId) {
		return userCouponMapper.selectUserCouponsByUserId(userId);
	}

	@Override
	public void updateUserCouponStatus(Long id, Integer status) {
		userCouponMapper.updateUserCouponStatus(id, status);
	}

	@Override
	public void deleteUserCouponById(Long id) {
		userCouponMapper.deleteUserCouponById(id);
	}

	@Override
	public boolean distributeCoupon(Long memberLevelId, Long couponTypeId) {
		// 查询优惠券类型信息
		CouponType couponType = couponTypeMapper.selectCouponTypeById(couponTypeId);
		if (couponType == null) {
			throw new RuntimeException("优惠券类型不存在");
		}

		// 查询所有符合条件的用户（根据会员级别）
		List<UserMember> userMembers = userMemberMapper.selectByMemberLevelId(memberLevelId);
		if (userMembers.isEmpty()) {
			throw new RuntimeException("没有符合条件的用户");
		}

		// 为每个用户发放优惠券
		for (UserMember userMember : userMembers) {
			UserCoupon userCoupon = new UserCoupon();
			userCoupon.setUserId(userMember.getUserId());
			userCoupon.setCouponTypeId(couponTypeId);
			userCoupon.setCouponCode(generateCouponCode()); // 生成优惠券码
			userCoupon.setStatus(UserCoupon.COUPON_STATUS_UNUSED); // 未使用
			userCoupon.setStartDate(new Date()); // 生效日期为当前时间

			// 计算失效日期
			if (couponType.getEffectiveDays() > 0) {
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, couponType.getEffectiveDays());
				userCoupon.setEndDate(calendar.getTime());
			}

			// 保存优惠券
			userCouponMapper.insertUserCoupon(userCoupon);
		}

		return true;
	}

	/**
	 * 生成优惠券码（示例逻辑）
	 * @return 优惠券码
	 */
	private String generateCouponCode() {
		return "COUPON-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
	}
}
